package com.ambimmort.shj.service.device;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.common.db_service.HibernateBaseDao;
import cn.net.greenet.common.ucagent_service.UcAgentSupport;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.*;
import cn.net.greenet.device.logic.ByteConvert;
import cn.net.greenet.device.logic.DeviceManagementImpl;
import cn.net.greenet.device.logic.IDeviceManagement;
import cn.net.greenet.device_deploy.servlet.DevDeployManageService;
import com.ambimmort.umessage.UcType;
import com.ambimmort.umessage.exceptions.UcTypeException;
import com.ambimmort.umessage.uc.outgoing.uvm.xC0;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by zyt on 2015/7/31.
 */
@Service
public class DeviceService {
    @Autowired
    private SessionFactory hibernateSessionFactory;
    
    ResultSet rs = null;
    BaseDao baseDao = null;

    private void init() {
        baseDao = new BaseDao();
    }

    private void close() {
        if (baseDao != null) {
            baseDao.close();
        }
    }

    /**
     * @param Dev_Name       DPI设备名
     * @param Dev_IP         DPI设备IP地址
     * @param Probe_Type     DPI采集类型 0:DPI 1:EU
     * @param DeploySiteName 本DPI设备部署站点名称
     * @param IDC_HouseID    本IDC设备部署机房名称
     * @param description    描述
     * @param result         策略库实例配置信息
     */
    public void createDevice(String Dev_Name, String Dev_IP, String Probe_Type, String DeploySiteName, String IDC_HouseID, String description, String result) {


        if (Dev_Name != null || Dev_IP != null || Probe_Type != null || DeploySiteName != null || IDC_HouseID != null || description != null || result != null) {
            if ("0".equals(Probe_Type)) {
                IDC_HouseID = "";
            }
            System.out.println("Probe_Type:" + Probe_Type + "\nIDC_HouseID:" + IDC_HouseID);
//            Session session = hibernateSessionFactory.openSession();
//            session.clear();

            init();
//            Transaction tx = session.beginTransaction();
            try {
                Dpiendpointbean bean = new Dpiendpointbean();
                bean.setName(Dev_Name);
                bean.setMasterIp(Dev_IP);
                bean.setProbeType(Integer.parseInt(Probe_Type));
                bean.setIdcHouseId(IDC_HouseID);
                bean.setDeploySiteName(DeploySiteName);
                bean.setDescription(description);
                bean.setPort(50000);
                bean.setIsClientChannelConnected(false);
                bean.setIsServerChannelConnected(false);
                bean.setIsHeartbeatOk(false);
                bean.setEnabled(false);
                String sql = "insert into Dpiendpointbean(name, deploySiteName,idcHouseId,port,enabled,isServerChannelConnected,isClientChannelConnected" +
                        ",probeType,masterIp,slaveIp,description,isHeartbeatOk) values(?,?,?,?,?,?,?,?,?,?,?,?)";
                Object[] params = {Dev_Name, DeploySiteName, IDC_HouseID, 50000, false, false, false, Integer.parseInt(Probe_Type), Dev_IP, null, description, false};
                baseDao.executeUpdate(sql, params);
//                session.save(bean);
                System.out.println("result:\n" + result);
//                JSONArray pris = JSONArray.fromObject(result);
//                System.out.println(pris);
//                for (int i = 0; i < pris.size(); i++) {
//                    JSONObject obj = pris.getJSONObject(i);
//                    System.out.println(obj);
//                    Policyrepositoryinstance pri = (Policyrepositoryinstance) session.get(Policyrepositoryinstance.class, Integer.parseInt(obj.getString("instanceId")));
//                    bean.getPolicyrepositoryinstances().add(pri);
//                    session.update(bean);
//                }
//                tx.commit();
            } catch (Exception e) {
                e.printStackTrace();
//                tx.rollback();
            } finally {
                close();
//                session.close();
            }
        }

    }

    /**
     * @param id
     */
    public void deleteDevice(String id) {
        if (id != null && id.matches("[0-9]*")) {

//            Session session = hibernateSessionFactory.openSession();
//            Transaction tx = session.beginTransaction();

            init();
//<<<<<<< HEAD
//            try {
//                int did = Integer.parseInt(id);
//                String[]a=new String[12];
                List list = new ArrayList();
                list.add(0, "Dpiendpointbean");
                list.add(1, "Ackincominglog");
                list.add(2, "Ackoutgoinglog");
                list.add(3, "Messageincominglog");
                list.add(4, "Messageoutgoinglog");
                list.add(5, "Messageoutgoingsendingqueue");
                list.add(6, "Policysynchronization");

                String sql;
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("BEGIN BATCH\n");
                for (int i = 0; i < list.size(); i++) {
                    stringBuffer.append("delete from " + list.get(i) + " where id = " + id + "\n");
                }
                stringBuffer.append("\nAPPLY BATCH;");
                sql = stringBuffer.toString();
                Object[] params = {};
                baseDao.executeUpdate(sql, params);
                stringBuffer.delete(0, stringBuffer.length());
//                stringBuffer.setLength(0);
                System.out.println(sql);


                System.out.println("==list 200==");
//                list.add(5,"MessageoutgoinglogManual");//表不存在

                List list1 = new ArrayList();
                list1.add(0, "Currentmessagesequenceno");//DPIEndPointBean_id
                list1.add(1, "Versionmanaged");//DPIEndPointBean_id
                list1.add(2, "Versionreported");//DPIEndPointBean_id
                stringBuffer.append("BEGIN BATCH\n");
                for (int i = 0; i < list1.size(); i++) {
                    stringBuffer.append("delete from " + list1.get(i) + " where DPIEndPointBean_id = " + id + "\n");
                }
                stringBuffer.append("\nAPPLY BATCH;");
                sql = stringBuffer.toString();
                baseDao.executeUpdate(sql, params);
                System.out.println(sql);
                stringBuffer.delete(0, stringBuffer.length());
//=======
//            try {
////                int did = Integer.parseInt(id);
////                String[]a=new String[12];
//                List list = new ArrayList();
//                list.add(0, "Dpiendpointbean");
//                list.add(1, "Ackincominglog");
//                list.add(2, "Ackoutgoinglog");
//                list.add(3, "Messageincominglog");
//                list.add(4, "Messageoutgoinglog");
//                list.add(5, "Messageoutgoingsendingqueue");
//                list.add(6, "Policysynchronization");
//>>>>>>> 422617fb51858de269c1236d9642364ac42cbd4f
//
//                String sql;
//                StringBuffer stringBuffer = new StringBuffer();
//                stringBuffer.append("BEGIN BATCH\n");
//                for (int i = 0; i < list.size(); i++) {
//                    stringBuffer.append("delete from " + list.get(i) + " where id = " + id + "\n");
//                }
//                stringBuffer.append("\nAPPLY BATCH;");
//                sql = stringBuffer.toString();
//                Object[] params = {};
//                baseDao.executeUpdate(sql, params);
//                stringBuffer.delete(0, stringBuffer.length());
//                System.out.println(sql);
//
//
//                System.out.println("==list 200==");
////                list.add(5,"MessageoutgoinglogManual");//表不存在
//
//                List list1 = new ArrayList();
//                list1.add(0, "Currentmessagesequenceno");//DPIEndPointBean_id
//                list1.add(1, "Versionmanaged");//DPIEndPointBean_id
//                list1.add(2, "Versionreported");//DPIEndPointBean_id
//                stringBuffer.append("BEGIN BATCH\n");
//                for (int i = 0; i < list1.size(); i++) {
//                    stringBuffer.append("delete from " + list1.get(i) + " where DPIEndPointBean_id = " + id + "\n");
//                }
//                stringBuffer.append("\nAPPLY BATCH;");
//                sql = stringBuffer.toString();
//                baseDao.executeUpdate(sql, params);
//                System.out.println(sql);
//                stringBuffer.delete(0, stringBuffer.length());
////
//                System.out.println("==list1 200==");


             sql = "delete from shj_db.dpiendpointbean where id = " + id;
            Object[] param = {};
            baseDao.executeUpdate(sql, param);
            close();
//                Dpiendpointbean bean = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(id));

            // delete Ackoutgoinglog set
//                Query deleteAckincominglogs = session.createQuery("delete Ackincominglog as c where c.dpiendpointbean.id=:did");

//                deleteAckincominglogs.setParameter("did", did);
//                deleteAckincominglogs.executeUpdate();

//                // delete Ackoutgoinglog set
//                Query deleteAckoutgoinglogs = session.createQuery("delete Ackoutgoinglog as c where c.dpiendpointbean.id=:did");
//                deleteAckoutgoinglogs.setParameter("did", did);
//                deleteAckoutgoinglogs.executeUpdate();
//
//                // delete Currentmessagesequencenos set
//                Query deleteCurrentmessagesequencenos = session.createQuery("delete Currentmessagesequenceno as c where c.id.dpiendPointBeanId=:did");
//                deleteCurrentmessagesequencenos.setParameter("did", did);
//                deleteCurrentmessagesequencenos.executeUpdate();
//
//                // delete Messageincominglogs
//                Query deleteMessageincominglogs = session.createQuery("delete Messageincominglog as c where c.dpiendpointbean.id=:did");
//                deleteMessageincominglogs.setParameter("did", did);
//                deleteMessageincominglogs.executeUpdate();
//
//                // delete MessageoutgoinglogManuals
//                Query deleteMessageoutgoinglogManuals = session.createQuery("delete MessageoutgoinglogManual as c where c.dpiendpointbean.id=:did");
//                deleteMessageoutgoinglogManuals.setParameter("did", did);
//                deleteMessageoutgoinglogManuals.executeUpdate();
//
//                // delete Messageoutgoinglogs
//                Query deleteMessageoutgoinglogs = session.createQuery("delete Messageoutgoinglog as c where c.dpiendpointbean.id=:did");
//                deleteMessageoutgoinglogs.setParameter("did", did);
//                deleteMessageoutgoinglogs.executeUpdate();
//
//                // delete Messageoutgoingsendingqueue
//                Query deleteMessageoutgoingsendingqueues = session.createQuery("delete Messageoutgoingsendingqueue as c where c.dpiendpointbean.id=:did");
//                deleteMessageoutgoingsendingqueues.setParameter("did", did);
//                deleteMessageoutgoingsendingqueues.executeUpdate();
//
//                // delete Messageoutgoingsendingqueue
//                Query deletePolicysynchronizations = session.createQuery("delete Policysynchronization as c where c.dpiendpointbean.id=:did");
//                deletePolicysynchronizations.setParameter("did", did);
//                deletePolicysynchronizations.executeUpdate();
//
//                // delete Versionmanaged
//                Query deleteVersionmanageds = session.createQuery("delete Versionmanaged as c where c.dpiendpointbean.id=:did");
//                deleteVersionmanageds.setParameter("did", did);
//                deleteVersionmanageds.executeUpdate();
//
//                // delete Versionreported
//                Query deleteVersionreporteds = session.createQuery("delete Versionreported as c where c.dpiendpointbean.id=:did");
//                deleteVersionreporteds.setParameter("did", did);
//                deleteVersionreporteds.executeUpdate();
//
//                // delete Messageoutgoingsendingqueue
//                Dpiendpointbean bean = (Dpiendpointbean) session.load(Dpiendpointbean.class, did);
//                bean.getPolicyrepositoryinstances().clear();
//                session.merge(bean);
//                session.delete(bean);
//                tx.commit();
//        }catch(Exception e){
//            e.printStackTrace();
////                tx.rollback();
//        }finally{
////                session.close();
//            close();
//        }
        }

    }

    /**
     * @param id
     * @param Dev_Name       DPI设备名
     * @param Dev_IP         DPI设备IP地址
     * @param Probe_Type     DPI采集类型 0:DPI 1:EU
     * @param DeploySiteName 本DPI设备部署站点名称
     * @param IDC_HouseID    本IDC设备部署机房名称
     * @param description    描述
     * @param result         策略库实例配置信息
     */
    public void editDevice(String id, String Dev_Name, String Dev_IP, String Probe_Type, String DeploySiteName, String IDC_HouseID, String description, String result) {
        if (id != null || Dev_Name != null || Dev_IP != null || Probe_Type != null || DeploySiteName != null || IDC_HouseID != null || description != null || result != null) {

            init();

            String sql = "select * from Dpiendpointbean where id= " + id;

            Object[] params = {};
//            Session session = hibernateSessionFactory.openSession();
//            session.clear();
//            Dpiendpointbean bean = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(id));
            rs = baseDao.executeSQL(sql, params);

//            ResultSet resultSet = baseDao.executeSQL(sql1, params);
//            if (bean != null) {
            try {
                String sql1 = "select * from Policyrepositoryinstance where id = " + id;

                if (rs.next()) {
                    Dpiendpointbean bean = new Dpiendpointbean();
                    try {
                        bean.setName(rs.getString(2));
                        bean.setMasterIp(rs.getString(10));
                        bean.setProbeType(rs.getInt(9));
                        bean.setIdcHouseId(rs.getString(4));
                        bean.setDeploySiteName(rs.getString(3));
                        bean.setDescription(rs.getString(12));
                        bean.getPolicyrepositoryinstances().clear();
                        sql = "    select\n" +
                                "        policyrepo0_.DPIEndPointBean_id as DPIEndPo1_27_1_,\n" +
                                "        policyrepo0_.PolicyRepositoryInstance_id as PolicyRe2_1_,\n" +
                                "        policyrepo1_.id as id32_0_,\n" +
                                "        policyrepo1_.PolicyRepositoryType_messageType as PolicyRe2_32_0_,\n" +
                                "        policyrepo1_.instanceName as instance3_32_0_,\n" +
                                "        policyrepo1_.reserved1 as reserved4_32_0_,\n" +
                                "        policyrepo1_.reserved2 as reserved5_32_0_ \n" +
                                "    from\n" +
                                "        dpiendpointbean_has_policyrepositoryinstance policyrepo0_ \n" +
                                "    inner join\n" +
                                "        shj_db.policyrepositoryinstance policyrepo1_ \n" +
                                "            on policyrepo0_.PolicyRepositoryInstance_id=policyrepo1_.id \n" +
                                "    where\n" +
                                "        policyrepo0_.DPIEndPointBean_id=" + id;
                        baseDao.executeSQL(sql, params);
                        JSONArray pris = JSONArray.fromObject(result);
                        for (int i = 0; i < pris.size(); i++) {
                            JSONObject obj = pris.getJSONObject(i);
                            Policyrepositoryinstance pri = new Policyrepositoryinstance();
                            ResultSet rs1 = baseDao.executeSQL(sql1, params);

                            while (rs1.next()) {
                                System.out.println();
                                pri.setId(rs1.getInt(1));
                                pri.setInstanceName(rs1.getString(2));
                                pri.setReserved1(rs1.getString(3));
                                pri.setReserved2(rs1.getString(4));
                                Policyrepositorytype p = new Policyrepositorytype();
                                p.setMessageType(rs1.getString(5));
                                pri.setPolicyrepositorytype(p);
                            }
                            bean.getPolicyrepositoryinstances().add(pri);
                            rs = baseDao.executeSQL(sql, params);
                        }


                    } catch (SQLException e) {
                        e.printStackTrace();
                    }

                    //                Transaction tx = session.beginTransaction();
                    //                sql = "update Dpiendpointbean set name = ?, deploySiteName = ?,idcHouseId = ?,port = ?,enabled = ?,isServerChannelConnected = ?,isClientChannelConnected = ?,probeType = ?,masterIp = ?,slaveIp = ?,description = ?,isHeartbeatOk = ?";

                    sql = "update\n" +
                            "    shj_db.dpiendpointbean \n" +
                            "set\n" +
                            "    name=?,\n" +
                            "    deploySiteName=?,\n" +
                            "    idcHouseId=?,\n" +
                            "    port=?,\n" +
                            "    enabled=?,\n" +
                            "    isServerChannelConnected=?,\n" +
                            "    isClientChannelConnected=?,\n" +
                            "    probeType=?,\n" +
                            "    masterIp=?,\n" +
                            "    slaveIp=?,\n" +
                            "    description=?,\n" +
                            "    isHeartbeatOk=? \n" +
                            "where\n" +
                            "    id=" + id;
                    //                try {
                    //                    Object [] p ={Dev_Name,Dev_IP};
                    //                    bean.setName(Dev_Name);
                    //                    bean.setMasterIp(Dev_IP);
                    //                    bean.setProbeType(Integer.parseInt(Probe_Type));
                    //                    bean.setIdcHouseId(IDC_HouseID);
                    //                    bean.setDeploySiteName(DeploySiteName);
                    //                    bean.setDescription(description);
                    //                    bean.getPolicyrepositoryinstances().clear();
                    //                    JSONArray pris = JSONArray.fromObject(result);
                    //                    for (int i = 0; i < pris.size(); i++) {
                    //                        JSONObject obj = pris.getJSONObject(i);
                    //                        Policyrepositoryinstance pri = (Policyrepositoryinstance) session.get(Policyrepositoryinstance.class, obj.getInt("instanceId"));
                    //                        bean.getPolicyrepositoryinstances().add(pri);
                    //                        session.update(bean);

                    //                    }
                    //                    session.update(bean);
                    //                    tx.commit();
                    params = new Object[]{Dev_Name, DeploySiteName, IDC_HouseID, 50000, false, false, false, Integer.parseInt(Probe_Type), Dev_IP, null, description, false};
                    System.out.println("bianjisql:" + sql);
                    baseDao.executeUpdate(sql, params);
                    close();
//                    sql = "insert into  dpiendpointbean_has_policyrepositoryinstance   (DPIEndPointBean_id, PolicyRepositoryInstance_id)  values   (?, ?)";
//                    params = new Object[]{id, id};
//                    baseDao.executeUpdate(sql, params);


                    //                } catch (Exception e) {
                    //                    tx.rollback();
                    //                } finally {
                    //                    session.clear();
                    //                    session.close();
                    //                    close();

                    //                }
                } else {
                    //                session.clear();
                    //                session.close();
                    close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                close();
            }
        }
    }

    /**
     * @param id
     * @param device_status DPI设备名
     */
    public void enableDevice(String id, String device_status) {
        System.out.println("enableservice");

        if (id != null || device_status != null) {
            init();
            Object[] params = {};
            String s = "select * from dpiendpointbean  where id=" + id;
            System.out.println(s);
            rs = baseDao.executeSQL(s, params);
//            Session session = hibernateSessionFactory.openSession();
//            session.clear();
//            Dpiendpointbean bean = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(id));
            try {
                if (rs.next()) {
                    //                Transaction tx = session.beginTransaction();
                    try {
                        //!device_status.equals("0")
                        Dpiendpointbean bean = new Dpiendpointbean();
                        bean.setId(rs.getInt(1));
                        bean.setName(rs.getString(2));
                        bean.setDeploySiteName(rs.getString(3));
                        bean.setIdcHouseId(rs.getString(4));
                        bean.setPort(rs.getInt(5));
                        bean.setEnabled(rs.getBoolean(6));
                        bean.setIsServerChannelConnected(rs.getBoolean(7));
                        bean.setIsClientChannelConnected(rs.getBoolean(8));
                        bean.setProbeType(rs.getInt(9));
                        bean.setMasterIp(rs.getString(10));
                        bean.setSlaveIp(rs.getString(11));
                        bean.setDescription(rs.getString(12));
                        bean.setIsHeartbeatOk(rs.getBoolean(13));


//                        bean.setName(rs.getString(2));
//                        bean.setMasterIp(rs.getString(3));
//                        bean.setProbeType(rs.getInt(9));
//                        bean.setIdcHouseId(rs.getString(4));
//                        bean.setDeploySiteName(rs.getString(3));
//                        bean.setDescription(rs.getString(12));
//                        bean.setPort(50000);
//                        bean.setIsClientChannelConnected(false);
//                        bean.setIsServerChannelConnected(false);
//                        bean.setIsHeartbeatOk(false);
//                        bean.setEnabled(true);
                        System.out.println("status====>" + rs.getBoolean(6));
                        if (rs.getBoolean(6) == false) {
                            init();
                            System.out.println("---------open---------");
                            s = "update dpiendpointbean set name=?,deploySiteName=?,idcHouseId=?,port=?,enabled=?,isServerChannelConnected=?,isClientChannelConnected=?," +
                                    "probeType=?,masterIp=?,slaveIp=?,description=?,isHeartbeatOk=? where id=" + id;
                            //                    bean.setEnabled("0".equals(device_status) ? false : true);
                            params = new Object[]{rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5), 1, rs.getInt(7), rs.getInt(8), rs.getInt(9), rs.getString(10), rs.getString(11), rs.getString(12), rs.getInt(13)};
                            baseDao.executeUpdate(s, params);
                            close();
                        } else {
                            init();
                            System.out.println("-------close--------");
                            s  = "update dpiendpointbean set name=?,deploySiteName=?,idcHouseId=?,port=?,enabled=?,isServerChannelConnected=?,isClientChannelConnected=?," +
                                    "probeType=?,masterIp=?,slaveIp=?,description=?,isHeartbeatOk=? where id=" + id;
                            //                    bean.setEnabled("0".equals(device_status) ? false : true);
                            params = new Object[]{rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5), 0, rs.getInt(7), rs.getInt(8), rs.getInt(9), rs.getString(10), rs.getString(11), rs.getString(12), rs.getInt(13)};
                            baseDao.executeUpdate(s, params);
                            close();
                        }
//                        bean.setEnabled("0".equals(device_status) ? false : true);
//                        String sql = "update dpiendpointbean set name=?,deploySiteName=?,idcHouseId=?,port=?,enabled=?,isServerChannelConnected=?,isClientChannelConnected=?," +
//                                "probeType=?,masterIp=?,slaveIp=?,description=?,isHeartbeatOk=? where id=" + id;
//                        //                    bean.setEnabled("0".equals(device_status) ? false : true);
//                        params = new Object[]{rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5), 1, rs.getInt(7), rs.getInt(8), rs.getInt(9), rs.getString(10), rs.getString(11), rs.getString(12), rs.getInt(13)};
//                        baseDao.executeUpdate(sql, params);
                        //                    session.update(bean);
                        //                    tx.commit();
//                        if (bean.isEnabled()) {
//                            boolean success = UcAgentSupport.getInstance().getApi().enableDPIEndPoint(bean.getId(), true);
//                            System.out.println("Enabled DPI (" + success + "):" + bean.getName());
//                        } else {
//                            boolean success = UcAgentSupport.getInstance().getApi().enableDPIEndPoint(bean.getId(), false);
//                            System.out.println("Disabled DPI (" + success + "):" + bean.getName());
//                        }
                    } catch (Exception e) {
                        //                    tx.rollback();
                        close();
                    } finally {
                        //                    session.clear();
                        //                    session.close();
                        close();
                    }
                } else {
                    //                session.close();
                    close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                close();
            }
            close();
        }

    }


    public String getDevDynamicInfoDevice(String id) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Messageincominglog bean = null;

        if (id != null && id.matches("[0-9]*")) {
            Session session = hibernateSessionFactory.openSession();
            HibernateBaseDao hibernateBaseDao = new HibernateBaseDao();

            String hql = "SELECT log From Messageincominglog AS log WHERE log.messageType=:messageType AND log.dpiendpointbean.id=" + id + " ORDER BY log.time DESC";
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("messageType", "0xC6");


            java.util.List MessageInComingLogList = hibernateBaseDao.getListLimit(hql, 1, params, session);

            Dpiendpointbean dpi = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(id));

            String heartBeatHql = "SELECT log From Messageincominglog AS log WHERE log.messageType=:messageType AND log.dpiendpointbean.id=" + id + " ORDER BY log.time DESC";
            Map<String, Object> heartBeatParams = new HashMap<String, Object>();
            heartBeatParams.put("messageType", "0xC1");
            java.util.List heartBeatList = hibernateBaseDao.getListLimit(heartBeatHql, 1, heartBeatParams, session);

            JSONObject ddObject = new JSONObject();

            if (heartBeatList.isEmpty()) {
                ddObject.put("device_status", "未响应");
                ddObject.put("lastHeartBeatTime", "最近五分钟内未收到心跳包");
            } else {
                Messageincominglog heartBeatLog = (Messageincominglog) heartBeatList.get(0);
                System.out.println("current time:" + format.format(new Date(System.currentTimeMillis())) + "\t LastHeartBeat:" + format.format(heartBeatLog.getTime()));
                if ((System.currentTimeMillis() - heartBeatLog.getTime().getTime()) > 300000) {
                    ddObject.put("device_status", "未响应");
                    ddObject.put("lastHeartBeatTime", "最近五分钟内未收到心跳包");
                } else {
                    ddObject.put("device_status", "正常");
                    ddObject.put("lastHeartBeatTime", format.format(heartBeatLog.getTime()));
                }
            }

            ddObject.put("isServerChannelConnected", dpi.isIsServerChannelConnected() ? "1" : "0");
            ddObject.put("isClientChannelConnected", dpi.isIsClientChannelConnected() ? "1" : "0");

            if (MessageInComingLogList.size() < 1 || !dpi.isEnabled()) {

                JSONArray Total_PortsArray = new JSONArray();
                JSONArray Total_CPUArray = new JSONArray();
                ddObject.put("Total_Ports", Total_PortsArray);
                ddObject.put("Total_CPU", Total_CPUArray);
//                out.println(ddObject);
                return ddObject.toString();
            } else if (MessageInComingLogList.size() > 0 || dpi.isEnabled()) {
                bean = (Messageincominglog) MessageInComingLogList.get(0);
                System.out.println("动态-time-:" + bean.getTime());
                byte[] msg = bean.getPacket();
                int ptr = 18;
                int Total_PostNum = ByteConvert.bytesToUbyte(new byte[]{msg[ptr]});//本DPI设备的总端口数
                ptr++;

                JSONArray Total_PortsArray = new JSONArray();
                for (int i = 0; i < Total_PostNum; i++) {
                    JSONObject Total_PortsObject = new JSONObject();
                    byte PortNo = msg[ptr];//端口编号
                    ptr++;
                    Total_PortsObject.put("PortNo", ByteConvert.bytesToUbyte(new byte[]{PortNo}) + "");

                    int PortInfoLength = msg[ptr] & 0xff;//端口描述信息长度
                    ptr++;
                    String PortInfo = new String(Arrays.copyOfRange(msg, ptr, ptr + PortInfoLength));//端口描述信息
                    ptr = ptr + PortInfoLength;
                    Total_PortsObject.put("PortInfo", PortInfo + "");

                    int PortUsage = msg[ptr] & 0xff;//本端口利用率
                    ptr++;
                    Total_PortsObject.put("PortUsage", PortUsage + "");
                    Total_PortsArray.add(Total_PortsObject);
                }
                int Total_CPU_Num = ByteConvert.bytesToUshort(Arrays.copyOfRange(msg, ptr, ptr + 2));//本DPI设备中所含的CPU数
                ptr = ptr + 2;
                JSONArray Total_CPUArray = new JSONArray();
                for (int i = 0; i < Total_CPU_Num; i++) {
                    JSONObject Total_CPUObject = new JSONObject();
                    int CPU_No = ByteConvert.bytesToUshort(Arrays.copyOfRange(msg, ptr, ptr + 2));//CPU编号
                    ptr = ptr + 2;
                    Total_CPUObject.put("CPU_No", CPU_No + "");

                    byte CPU_Usage = msg[ptr];//本CPU利用率
                    ptr++;
                    Total_CPUObject.put("CPU_Usage", ByteConvert.bytesToUbyte(new byte[]{CPU_Usage}) + "");
                    System.out.println(Total_CPUObject);
                    Total_CPUArray.add(Total_CPUObject);
                }
                ddObject.put("Total_Ports", Total_PortsArray);
                ddObject.put("Total_CPU", Total_CPUArray);
//                out.println(ddObject);
                return ddObject.toString();
            }
//session.clear();
            /* TODO output your page here. You may use following sample code. */
            session.close();
        } else {
            return "[" + id + "]";
        }
//        out.close();

        return null;
    }

    /**
     * @param id 设备ID
     * @return
     */
    public String getDevPolicyBankInfoDevice(String id) {
        if (id != null && id.matches("[0-9]*")) {
            IDeviceManagement iDeviceManagement = new DeviceManagementImpl();
            return iDeviceManagement.getDevPolicyBankInfo(id).toString();
        } else {
            return "id:" + id;
        }
    }

    /**
     * @param id 设备ID
     */
    public String getDevStaticInfoServiceDevice(String id) {
        if (id != null && id.matches("[0-9]*")) {
            try {
                Messageincominglog bean = null;
                SessionFactory sf = HibernateUtil.getSessionFactory();
                Session session = sf.openSession();
                session.clear();

//            SQLQuery query=session.createSQLQuery(sql);
                String hql = "From Messageincominglog  WHERE messageType=:messageType AND dpiendpointbean.id=" + id + " ORDER BY time DESC";
                HibernateBaseDao hbd = new HibernateBaseDao();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("messageType", "0xC5");
                List MessageInComingLogList = hbd.getListLimit(hql, 1, map, session);
//            Query query = session.createQuery("From Messageincominglog  WHERE messageType=:messageType AND dpiendpointbean.id=" + id + " ORDER BY time DESC");
//            query.setParameter("messageType", "0xc5");
//            query.setFirstResult(0).setMaxResults(1).list();
//            System.out.println("query:" + query.getQueryString());

//            List MessageInComingLogList = query.list();
//            System.out.println("MessageInComingLogList:" + MessageInComingLogList.size());
                Dpiendpointbean dpi = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(id));

                System.out.println("开启状态：" + dpi.isEnabled());
                if (MessageInComingLogList.isEmpty() || !dpi.isEnabled()) {
                    JSONObject staticObiect = new JSONObject();
                    staticObiect.put("SoftwareVersion", "-");
                    staticObiect.put("device_enabled", dpi.isEnabled() ? "1" : "0");
                    int probeType = dpi.getProbeType();

                    staticObiect.put("Probe_Type", probeType + "");//DPI采集类型
                    if (0 == probeType) {
                        staticObiect.put("DeploySiteName", dpi.getDeploySiteName() + "");//本DPI设备部署站点名

                        staticObiect.put("IDC_HouseID", "-");//本DPI设备部署站点名称
                    } else if (1 == probeType) {

                        staticObiect.put("DeploySiteName", dpi.getDeploySiteName() + "");//本DPI设备部署站点名

                        staticObiect.put("IDC_HouseID", dpi.getIdcHouseId() + "");//本DPI设备部署站点名称
                    }
                    staticObiect.put("Deploy_Mode", "-");//本DPI设备在现网中的部署模式

                    staticObiect.put("Total_Capability", "-");//DPI设备总分析能力( 以Gbps为单位)，单向

                    staticObiect.put("SlotNum", "-");//DPI设备总槽位数

                    staticObiect.put("PreProcSlotNum", "-");//DPI设备预处理模块占用槽位数

                    staticObiect.put("AnalysisSlotNum", "-");//DPI设备分析模块占用槽位数

                    staticObiect.put("GPSlotNum", "-");//DPI 通用 (General Purpose)模块占用槽位数
                    JSONArray PortsTypeNumArray = new JSONArray();
                    for (int i = 0; i < 1; i++) {
                        JSONObject PortsTypeNumObject = new JSONObject();
                        PortsTypeNumObject.accumulate("PortType", "-");//本DPI设备现有端口类型
                        PortsTypeNumObject.accumulate("Ports", '1');
                        JSONArray PortsArray = new JSONArray();
                        for (int j = 0; j < 1; j++) {
                            JSONObject PortsNumObject = new JSONObject();
                            PortsNumObject.put("PortNo", "-");//本端口的编号
                            PortsNumObject.put("PortDescription", "-");////本端口描述信息
                            PortsNumObject.put("M_LinkID", "-");//本端口监控链路编号
                            //本端口监控链路描述信息长度
                            PortsNumObject.put("M_LinkDesc", "-");//监控链路描述信息
                            PortsTypeNumArray.add(PortsNumObject);
                        }
                    }
                    staticObiect.put("Ports", PortsTypeNumArray);
                    return staticObiect.toString();
                } else if (MessageInComingLogList.size() > 0) {

                    JSONObject staticObiect = new JSONObject();
                    bean = (Messageincominglog) MessageInComingLogList.get(0);
                    System.out.println("静态-time-:" + bean.getTime());
                    byte[] msg = bean.getPacket();
                    int ptr = 18;
                    int SoftwareVersion = (int) ByteConvert.bytesToUint(Arrays.copyOfRange(msg, ptr, ptr + 4));//DPI软件版本号
                    ptr = ptr + 4;
                    staticObiect.put("SoftwareVersion", SoftwareVersion);
                    staticObiect.put("device_enabled", dpi.isEnabled() ? "1" : "0");
                    int Probe_Type = msg[ptr] & 0xff;//DPI采集类型
                    ptr++;
                    staticObiect.put("Probe_Type", Probe_Type);
                    int DeploySiteNameLength = msg[ptr] & 0xff;//本DPI设备部署站点名长度
                    ptr++;
                    String DeploySiteName = new String(Arrays.copyOfRange(msg, ptr, ptr + DeploySiteNameLength));//本DPI设备部署站点名
                    ptr = ptr + DeploySiteNameLength;
                    staticObiect.put("DeploySiteName", DeploySiteName);
                    int IDC_HouseID_Length = msg[ptr] & 0xff;//EU 设 备 部 署 机 房HouseID的长度
                    ptr++;
                    String IDC_HouseID = new String(Arrays.copyOfRange(msg, ptr, ptr + IDC_HouseID_Length));//本DPI设备部署站点名称
                    ptr = ptr + IDC_HouseID_Length;
                    staticObiect.put("IDC_HouseID", IDC_HouseID);

                    int Deploy_Mode = msg[ptr] & 0xff;//本DPI设备在现网中的部署模式
                    ptr++;
                    staticObiect.put("Deploy_Mode", Deploy_Mode + "");

                    int Total_Capability = ByteConvert.bytesToUshort(Arrays.copyOfRange(msg, ptr, ptr + 2));//DPI设备总分析能力( 以Gbps为单位)，单向
                    ptr = ptr + 2;
                    staticObiect.put("Total_Capability", Total_Capability + "");//DPI设备总分析能力( 以Gbps为单位)，单向

                    int SlotNum = msg[ptr] & 0xff;//DPI设备总槽位数
                    ptr++;
                    staticObiect.put("SlotNum", SlotNum + "");

                    int PreProcSlotNum = msg[ptr] & 0xff;//DPI设备预处理模块占用槽位数
                    ptr++;
                    staticObiect.put("PreProcSlotNum", PreProcSlotNum + "");

                    int AnalysisSlotNum = msg[ptr] & 0xff;//DPI设备分析模块占用槽位数
                    ptr++;
                    staticObiect.put("AnalysisSlotNum", AnalysisSlotNum + "");

                    int GPSlotNum = msg[ptr] & 0xff;//DPI 通用 (General Purpose)模块占用槽位数
                    ptr++;
                    staticObiect.put("GPSlotNum", GPSlotNum + "");

                    int PortsTypeNum = msg[ptr] & 0xff;//本DPI设备所配备的端口类型数
                    ptr++;

                    JSONArray PortsTypeNumArray = new JSONArray();

                    for (int i = 0; i < PortsTypeNum; i++) {
                        JSONObject PortsTypeNumObject = new JSONObject();
                        int PortType = msg[ptr] & 0xff;//本DPI设备现有端口类型
                        ptr++;

                        int PortsNum = msg[ptr] & 0xff;//属于本类型的端口数
                        ptr++;
//                    JSONArray PortsArray = new JSONArray();
                        JSONArray PortsArray = new JSONArray();

                        for (int j = 0; j < PortsNum; j++) {
                            JSONObject PortsNumObject = new JSONObject();
                            PortsNumObject.accumulate("PortType", PortType + "");
                            int PortNo = msg[ptr] & 0xff;//本端口的编号
                            ptr++;
                            PortsNumObject.put("PortNo", PortNo + "");

                            int PortDescLength = msg[ptr] & 0xff;//本端口描述信息长度
                            ptr++;

                            String PortDescription = new String(Arrays.copyOfRange(msg, ptr, ptr + PortDescLength));//本端口描述信息
                            ptr = ptr + PortDescLength;
                            PortsNumObject.put("PortDescription", PortDescription);

                            int M_LinkID = msg[ptr] & 0xff;//本端口监控链路编号
                            ptr++;
                            PortsNumObject.put("M_LinkID", M_LinkID + "");

                            int M_LinkDescLength = msg[ptr] & 0xff;//本端口监控链路描述信息长度
                            ptr++;
                            String M_LinkDesc = new String(Arrays.copyOfRange(msg, ptr, ptr + M_LinkDescLength));//监控链路描述信息
                            ptr = ptr + M_LinkDescLength;
                            PortsNumObject.put("M_LinkDesc", M_LinkDesc);
                            PortsTypeNumArray.add(PortsNumObject);
                        }

                    }
                    staticObiect.put("Ports", PortsTypeNumArray);
                    return staticObiect.toString();
                }
                session.close();
            } catch (Exception e) {
                e.printStackTrace();
                return "[]";
            } finally {

            }
        } else {
            return "[" + id + "]";
        }
        return null;
    }

    /**
     * @param id
     */
    public String getDevice(String id) {
        init();
        if (id != null && id.matches("[0-9]*")) {
//            Session session = hibernateSessionFactory.openSession();
//            session.clear();
//            Dpiendpointbean dpi = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(id));
            String sql = "select * from Dpiendpointbean where id =" + id;
            Object[] params = {};
            rs = baseDao.executeSQL(sql, params);
            JSONObject rst = new JSONObject();
            try {
                while (rs.next()) {
                    rst.put("Dev_Name", rs.getString("name"));
                    rst.put("Dev_IP", rs.getString("masterIp"));
                    rst.put("Probe_Type", rs.getInt("probeType"));
                    rst.put("DeploySiteName", rs.getString("deploySiteName"));
                    rst.put("IDC_HouseID", rs.getString("idcHouseId"));
                    rst.put("description", rs.getString("description"));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }


//            Set s = dpi.getPolicyrepositoryinstances();
//            JSONArray ps = new JSONArray();
            Policyrepositoryinstance tmp = null;
//            for (Object o : s) {
//                tmp = (Policyrepositoryinstance) o;
//                JSONObject obj = new JSONObject();
//                obj.put("strategy_id", tmp.getId());
//                obj.put("Message_Type", tmp.getPolicyrepositorytype().getMessageType());
//                obj.put("strategy_name", tmp.getInstanceName());
//                ps.add(obj);
//            }

            JSONArray jSONArray = new JSONArray();
            try {
                while (rs.next()) {
                    //                i++;
                    //                bean = (Dpiendpointbean) l.get(i);
                    //                bean = new Dpiendpointbean();
                    JSONObject jSONObject = new JSONObject();
                    jSONObject.put("strategy_id", tmp.getId());
                    jSONObject.put("Message_Type", tmp.getPolicyrepositorytype().getMessageType());
                    jSONObject.put("strategy_name", tmp.getInstanceName());
                    jSONArray.add(jSONObject);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rst.put("result", jSONArray);
            close();
//            session.close();
//            out.print(rst);
            return rst.toString();
        } else {
            return "[" + id + "]";

        }
//        out.close();

    }

    public String listAllPolicyRepositoryInstancesDevice() {
        init();
//        Session session = hibernateSessionFactory.openSession();
//       String sql =  "select policyrepo0_.id as id32_, policyrepo0_.PolicyRepositoryType_messageType as PolicyRe2_32_, policyrepo0_.instanceName as instance3_32_, policyrepo0_.reserved1 as reserved4_32_, policyrepo0_.reserved2 as reserved5_32_ from shj_db.policyrepositoryinstance policyrepo0_";
        String sql = "select * from policyrepositoryinstance policyrepo0_";
//        String sql = "select * from Policyrepositoryinstance";
        try {
//            List l = session.createQuery("From Policyrepositoryinstance").list();
//            List l = new ArrayList();
            Object[] params = {};
            rs = baseDao.executeSQL(sql, params);
//            while (rs.next()) {
//                l.add(rs.next());
//            }
//            JSONArray rst = new JSONArray();
//            Policyrepositoryinstance tmp = null;
//            for (int i = 0; i < l.size(); i++) {
//                System.out.println(l.get(i));
//                tmp = (Policyrepositoryinstance) l.get(i);
//                JSONObject obj = new JSONObject();
//                obj.put("strategy_id", tmp.getId());
//                obj.put("Message_Type", tmp.getPolicyrepositorytype().getMessageType());
//                obj.put("strategy_name", tmp.getInstanceName());
//                rst.add(obj);
//            }
            JSONArray jSONArray = new JSONArray();
            while (rs.next()) {
                JSONObject jSONObject = new JSONObject();
                jSONObject.put("strategy_id", rs.getString("id"));
                jSONObject.put("Message_Type", rs.getString("PolicyRepositoryType_messageType"));
                jSONObject.put("strategy_name", rs.getString("instanceName"));
                jSONArray.add(jSONObject);
            }
            try {
                /* TODO output your page here. You may use following sample code. */
//                out.println(rst);
                return jSONArray.toString();
            } catch (Exception e) {
                return "[]";
            }
        } catch (Exception e) {
            return "[]";
        } finally {
//            session.close();
            close();
        }

//        try (PrintWriter out = response.getWriter()) {
//           IDeviceManagement iDeviceManagement = new DeviceManagementImpl();
//           out.println(iDeviceManagement.getEveryPolicyBank());
//        }
    }

    /**
     * @param type
     */
    public String listDevice(String type) {
        System.out.println("==listDevice==" + type);

//        Session session = hibernateSessionFactory.openSession();
//        session.clear();
//        System.out.println("==session=="+session);
        init();
        try {
            Dpiendpointbean bean = null;
            java.util.List l = null;
            Object[] params = {};
            if ("eu".equals(type)) {
//                l = session.createQuery("FROM Dpiendpointbean  WHERE probeType =1").list();
                rs = baseDao.executeSQL("selct * from Dpiendpointbean WHERE probeType =1", params);
            } else if ("dpi".equals(type)) {
//                l = session.createQuery("FROM Dpiendpointbean  WHERE probeType =0").list();
                rs = baseDao.executeSQL("select * FROM Dpiendpointbean  WHERE probeType =0", params);
            } else if ("all".equals(type)) {
//                l = session.createQuery("FROM Dpiendpointbean").list();
                rs = baseDao.executeSQL("select * FROM Dpiendpointbean", params);
            }
//
            JSONArray jSONArray = new JSONArray();
//            System.out.println("Dpiendpointbean-size:"+l.size());
//            int i=0;
            while (rs.next()) {
//                i++;
//                bean = (Dpiendpointbean) l.get(i);
//                bean = new Dpiendpointbean();
                JSONObject jSONObject = new JSONObject();
                jSONObject.put("name", rs.getString("name"));
                jSONObject.put("ip", rs.getString("masterIp"));
                jSONObject.put("id", rs.getInt("id"));
                jSONObject.put("isCCOn", rs.getBoolean("isClientChannelConnected") ? "1" : "0");
                jSONObject.put("isSCOn", rs.getBoolean("isServerChannelConnected") ? "1" : "0");
                jSONObject.put("isEnabled", rs.getBoolean("enabled") ? "1" : "0");
                jSONArray.add(jSONObject);
            }
//            for (int i = 0; i < l.size(); i++) {
//                bean = (Dpiendpointbean) l.get(i);
//                JSONObject jSONObject = new JSONObject();
//                jSONObject.put("name", bean.getName());
//                jSONObject.put("ip", bean.getMasterIp());
//                jSONObject.put("id", bean.getId() + "");
//                jSONObject.put("isCCOn", bean.isIsClientChannelConnected() ? "1" : "0");
//                jSONObject.put("isSCOn", bean.isIsServerChannelConnected() ? "1" : "0");
//                jSONObject.put("isEnabled", bean.isEnabled() ? "1" : "0");
//                jSONArray.add(jSONObject);
//            }
//
//            try {
//                /* TODO output your page here. You may use following sample code. */
            return jSONArray.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "[]";
        } finally {
            close();
//        } catch (Exception e) {
//            return "[]";
//            session.close();
        }
    }

    /**
     * @param id
     * @return
     */
    public void sendBasicInfoDevice(String id) {
        if (id != null) {
            init();
            Dpiendpointbean bean = new Dpiendpointbean();
            Object[] params = {};
            rs = baseDao.executeSQL("select * from Dpiendpointbean", params);
            try {
                while (rs.next()) {
                    System.out.println("ID:=======>" + rs.getString(1));
                    bean.setId(rs.getInt(1));
                    bean.setName(rs.getString(2));
                    bean.setDeploySiteName(rs.getString(3));
                    bean.setIdcHouseId(rs.getString(4));
                    bean.setPort(rs.getInt(5));
                    bean.setEnabled(rs.getBoolean(6));
                    bean.setIsServerChannelConnected(rs.getBoolean(7));
                    bean.setIsClientChannelConnected(rs.getBoolean(8));
                    bean.setProbeType(rs.getInt(9));
                    bean.setMasterIp(rs.getString(10));
                    bean.setSlaveIp(rs.getString(11));
                    bean.setDescription(rs.getString(12));
                    bean.setIsHeartbeatOk(rs.getBoolean(13));

                }

//                bean.setName(rs.getString(2));
//                bean.setMasterIp(rs.getString(10));
//                bean.setProbeType(rs.getInt(9));
//                bean.setIdcHouseId(rs.getString(4));
//                bean.setDeploySiteName(rs.getString(3));
//                bean.setDescription(rs.getString(12));
//                bean.setPort(50000);
//                bean.setIsClientChannelConnected(true);
//                bean.setIsServerChannelConnected(false);
//                bean.setIsHeartbeatOk(false);
//                bean.setEnabled(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }

//            Session session = hibernateSessionFactory.openSession();
//            Dpiendpointbean bean = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(id));
            if (bean != null) {
//                Transaction tx = session.beginTransaction();
                try {
                    xC0 c0 = new xC0();
                    c0.setDev_Name(UcType.newUString_UINT1(bean.getName()));
                    c0.setDeploySiteName(UcType.newUString_UINT1(bean.getDeploySiteName()));
                    c0.setProbe_Type(UcType.newUINT1(bean.getProbeType()));
                    c0.setiDC_HouseID(UcType.newUString_UINT1(bean.getIdcHouseId()));
                    c0.getHeader().setMessageType(new UcType.UINT1(new byte[]{(byte) 0xc0}));
                    try {
                        c0.getHeader().setMessageNo(UcType.newUINT4(0l));
                        c0.getHeader().setMessageSequenceNo(UcType.newUINT4(1l));
                    } catch (UcTypeException ex) {
                        Logger.getLogger(xC0.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    Messageoutgoingsendingqueue qlog = new Messageoutgoingsendingqueue();
                    qlog.setCreateTime(new Date(System.currentTimeMillis()));
                    qlog.setDpiendpointbean(bean);
                    qlog.setMessageNo(0);
                    qlog.setMessageSequenceNo(1);
                    qlog.setMessageType("0xC0");
                    qlog.setType(1);
                    qlog.setPacket(c0.toBytes());
                    String s = "delete from Messageoutgoingsendingqueue where id="+ id;
                    System.out.println("sql s ===="+s);
                    baseDao.executeUpdate(s,params);
                    params = new Object[]{"0xC0", 0, 1, 0, 1, id, new Date(System.currentTimeMillis()), c0.toBytes(), bean.getId()};
                    baseDao.executeUpdate("insert into  Messageoutgoingsendingqueue values(?,?,?,?,?,?,?,?,?)", params);
                    close();
//                    session.save(qlog);
//                    tx.commit();
//                    UcAgentSupport.getInstance().getApi().msg_send_manaul_by_MessageTypeAndDevice(bean.getName(), "0xC0");
                    System.out.println("Sent DPI (" + bean.getName() + "):");
//                    try {
//                        /* TODO output your page here. You may use following sample code. */
//                        out.println("{\"result\":\"true\"}");
//                    } catch (Exception e) {
//                        out.println("{\"result\":\"false\"}");
//                    }

                } catch (Exception e) {
//                    tx.rollback();
//                    out.println("{\"result\":\"false\"}");
                    close();
                } finally {
//                    out.close();
//                    session.close();
                    close();
                }
            } else {
//                out.println("{\"result\":\"false\"}");
//                out.close();
//                session.close();
                close();
            }
        }

    }

    /**
     * @return
     */
    public String verifyDevNameDevice() {
//        Session session = hibernateSessionFactory.openSession();
        init();
        try {
            Dpiendpointbean bean = null;
            Object[] params = {};
            //SELECT dpi FROM Dpiendpointbean AS dpi WHERE dpi.name=:name
            baseDao.executeSQL("insert into Dpiendpointbean values(?,?,?,?,?,?,?,?,?,?,?,?)", params);
//            Query query = session.createQuery("FROM Dpiendpointbean");
//            query.setParameter("name", name);
//            List l = query.list();
            List l = new ArrayList();
            while (rs.next()) {
                l.add(rs.next());
            }
            JSONArray jSONArray = new JSONArray();
            for (int i = 0; i < l.size(); i++) {
                bean = (Dpiendpointbean) l.get(i);
                jSONArray.add(bean.getName());
            }

//            }
//            if(l.isEmpty()){
//            out.println(jSONArray);
//            }else{
//                out.println("{\"result\":\"false\"}");
//            }
            return jSONArray.toString();
        } catch (Exception e) {
//            out.println("[]");
            return "[]";
        } finally {
//            out.close();
//            session.close();
            close();
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //device_deploy.*

    /**
     * @param ip             DPI设备IP地址
     * @param deploySiteName
     * @param belongTo
     * @param deviceNo
     * @return
     */
    public String createDevDepDevice(String ip, String deploySiteName, String belongTo, String deviceNo) {
        boolean flag = false;

            /* TODO output your page here. You may use following sample code. */
        DevDeployManageService udd = new DevDeployManageService();
        flag = udd.insert(ip, deploySiteName, belongTo, deviceNo);
        return "{\"result\":\"" + flag + "\"}";
    }

    /**
     * @param id
     * @return
     */
    public String deleteDevDepDevice(Long id) {
        boolean flag = false;
            /* TODO output your page here. You may use following sample code. */
        DevDeployManageService udd = new DevDeployManageService();
        flag = udd.delete(id);
        return "{\"result\":\"" + flag + "\"}";
    }

    /**
     * @param id_str
     * @param ip             DPI设备IP地址
     * @param deploySiteName
     * @param belongTo
     * @param deviceNo
     * @return
     */
    public String editDevDepDevice(String id_str, String ip, String deploySiteName, String belongTo, String deviceNo) {
        boolean flag = false;
        try {
            long id = Long.parseLong(id_str);
                /* TODO output your page here. You may use following sample code. */
            DevDeployManageService udd = new DevDeployManageService();
            flag = udd.update(ip, deploySiteName, belongTo, deviceNo, id);
        } catch (Exception e) {
        }
        return "{\"result\":\"" + flag + "\"}";
    }

    /**
     * @return
     */
    public String listAllDevice() {
        DevDeployManageService udd = new DevDeployManageService();
        JSONArray arr = udd.findAll();
        return arr.toString();
    }

}
